package com.ujiuye.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

/**
 * druid 数据库连接池工具类
 */
public class DruidUtils {

    // 获取数据源
    public static DataSource getDataSource(){
// 1. 读取配置文件
        InputStream in = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
// 2. 创建属性对象
        Properties prop = new Properties();
        DataSource dataSource = null;

        try {
// 3. 将配置信息存放到属性对象
            prop.load(in);
// 4. 创建数据源
            dataSource = DruidDataSourceFactory.createDataSource(prop);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dataSource;
    }

    /**
     * 创建dbUtils 的核心操作工具QueryRunner 对象,并传递了数据源
     * @return QueryRunner 对象
     */
    public static QueryRunner getQueryRunner(){
        return new QueryRunner(getDataSource()) ;
    }


    @Test
    public void test() throws SQLException {
        System.out.println(getDataSource().getConnection());
    }
}
